import orm from '@main/db/orm'
import { IpcHandler, IpcInvoke } from '@main/decorator/ipc.decorator'
import { Injectable } from '@nestjs/common'
import type { PluginLocalTool } from '@shared/types/entity'
import { pluginLocalTool } from '@shared/constant/schema'
import { and, ilike, eq, inArray } from 'drizzle-orm'

@IpcHandler('pluginLocalTool')
@Injectable()
export class PluginLocalToolApi {
  @IpcInvoke('getList')
  async getList(q: PluginLocalTool): Promise<PluginLocalTool[]> {
    return await orm
      .select()
      .from(pluginLocalTool)
      .where(and(q.name ? ilike(pluginLocalTool.name, q.name) : undefined))
  }

  @IpcInvoke('getPage')
  async getPage(q: PluginLocalTool, pageSize: number, pageNum: number): Promise<PluginLocalTool[]> {
    return await orm
      .select()
      .from(pluginLocalTool)
      .where(and(q.name ? ilike(pluginLocalTool.name, q.name) : undefined))
      .limit(pageSize)
      .offset(pageSize * pageNum)
  }

  @IpcInvoke('getCount')
  async getCount(q: PluginLocalTool): Promise<number> {
    return await orm.$count(
      pluginLocalTool,
      and(q.name ? ilike(pluginLocalTool.name, q.name) : undefined)
    )
  }

  @IpcInvoke('add')
  async add(e: PluginLocalTool): Promise<PluginLocalTool> {
    return await orm
      .insert(pluginLocalTool)
      .values(e)
      .returning()
      .then((res) => res[0])
  }

  @IpcInvoke('editByMark')
  async editById(e: PluginLocalTool): Promise<PluginLocalTool> {
    return await orm
      .update(pluginLocalTool)
      .set(e)
      .where(eq(pluginLocalTool.mark, e.mark))
      .returning()
      .then((res) => res[0])
  }

  @IpcInvoke('deleteByMark')
  async deleteById(mark: string): Promise<number> {
    const res = await orm
      .delete(pluginLocalTool)
      .where(eq(pluginLocalTool.mark, mark))
      .returning({ mark: pluginLocalTool.mark })
    return res.length
  }

  @IpcInvoke('deleteByMarks')
  async deleteByIds(marks: string[]): Promise<number> {
    const res = await orm
      .delete(pluginLocalTool)
      .where(inArray(pluginLocalTool.mark, marks))
      .returning({ mark: pluginLocalTool.mark })
    return res.length
  }
}
